﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Shohdi.DataHandler;
using DatabaseComponent;
using System.IO;

public partial class FoldersEN : System.Web.UI.Page
{

    public string FolderImageName = "";


    long FoldersID
    {
        get
        {
            if (ViewState["FoldersID"] == null)
            {
                ViewState["FoldersID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["FoldersID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["FoldersID"].ToString()] = obj;

            }

            return (long)Session[ViewState["FoldersID"].ToString()];

        }
        set
        {
            if (ViewState["FoldersID"] == null)
            {
                ViewState["FoldersID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["FoldersID"].ToString()] = value;
        }
    }


    Folders objFolders
    {
        get
        {
            if (ViewState["objFolders"] == null)
            {
                ViewState["objFolders"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["objFolders"].ToString()] == null)
            {
                Session[ViewState["objFolders"].ToString()] = new Folders();

            }

            return (Folders)Session[ViewState["objFolders"].ToString()];

        }
        set
        {
            if (ViewState["objFolders"] == null)
            {
                ViewState["objFolders"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["objFolders"].ToString()] = value;
        }
    }



    



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Folders_page))
            Response.Redirect("LoginEN.aspx");



        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_folders_page))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }





    }





    /// <summary>
    /// this function will check RequestID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        if (objFolders.ID != -1)
        {
            FoldersID = objFolders.ID;
            btnDelete.Visible = true;

        }
        else
        {
            btnDelete.Visible = false;
        }


        //if (Request["ID"] != null)
        //{
        //    try
        //    {
        //        FoldersID = long.Parse(Request["ID"]);
        //        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);
        //        List<Folders> lstFolders = objFoldersDB.getFoldersByID(FoldersID);
        //        if (lstFolders.Count > 0)
        //        {
        //            if (lstFolders[0].StatusID == 2)
        //                throw new Exception();

        //            objFolders = lstFolders[0];
                    
        //        }
        //        else
        //        {
        //            throw new Exception();

        //        }


        //    }
        //    catch
        //    {
        //        Response.Redirect("FoldersViewEN.aspx");
        //    }
        //}
        //else
        //{
        //    btnDelete.Visible = false;
           
        //}
    }


    


    /// <summary>
    /// this will bind the user data to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        if (FoldersID != -1)
        {

            if (objFolders.ParentID != null)
            {
                fc1.set(objFolders.ParentID.Value);
            }
            else
                fc1.set(-1);




            txtFolderNameAR.Text = objFolders.FolderNameAR;
            txtFolderNameEN.Text = objFolders.FolderNameEN;

            


            
        }


        imgFolderImage.Src = objFolders.FolderImageUrl;

    }



    


    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {

        objFolders.ParentID = fc1.get();

        if (objFolders.ParentID == -1)
            objFolders.ParentID = null;

        objFolders.FolderNameAR = txtFolderNameAR.Text;
        objFolders.FolderNameEN = txtFolderNameEN.Text;





        objFolders.StatusID = 1;


        try
        {

            if (flFolderImage.HasFile)
            {
                FileInfo fi = new FileInfo(flFolderImage.FileName);

                string strFileName = System.Guid.NewGuid().ToString() +  fi.Extension;

                flFolderImage.SaveAs(Server.MapPath("./FolderImages/" + strFileName));

                FolderImageName = strFileName;



            }
            else
            {
                FolderImageName = "";
            }

        }

        catch
        {
            FolderImageName = "";
        }



            

        
    }


    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {
        long oldID = fc1.get();

        fc1.set(-1);

        txtFolderNameAR.Text = "";
        txtFolderNameEN.Text = "";

        
        objFolders = new Folders();

        fc1.refreshTree();
        
        fc1.set(oldID);


        oldID = fcSelectFolder.get();

        fcSelectFolder.refreshTree();

        fcSelectFolder.set(oldID);

        imgFolderImage.Src = (new Folders()).FolderImageUrl;
    }





    protected void Page_Load(object sender, EventArgs e)
    {


        Persons currentPerson = GlobalVars.getCurrentPerson();




        if (!Page.IsPostBack)
        {
            
            checkSecurityAndCustomizePage(currentPerson);

            checkID();
            

            BindAllControls();

            
            

        }
    }



   







   




    /// <summary>
    /// this function will Save the department
    /// </summary>
    protected void Save()
    {
        

        if (checkForRepeats())
        {
            bool isInserted = false;

            FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);
            if (objFolders.ID == -1)
            {
                isInserted = true;
                objFoldersDB.Insert(objFolders);
                

            }
            else
            {
                isInserted = false;
                objFoldersDB.Update(objFolders);
               
            }


            if (FolderImageName != "")
            {

                FolderImagesDB objFolderImagesDB = new FolderImagesDB(ConnectionStrings.LMS);

                List<FolderImages> lstFolderImages = objFolderImagesDB.getFolderImagesByFolderID(objFolders.ID);

                foreach (FolderImages obj in lstFolderImages)
                {
                    objFolderImagesDB.Delete(obj);
                }


                FolderImages objFolderImages = new FolderImages();
                objFolderImages.FolderID = objFolders.ID;
                objFolderImages.FolderImage = FolderImageName;
                objFolderImagesDB.Insert(objFolderImages);



            }


            if (isInserted)
            {
                clearAllControls();
                lblResult.Text = "Data saved ok.";
            }
            else
            {
                BindAllControls();
                fc1.refreshTree();
                fcSelectFolder.refreshTree();
                lblResult.Text = "Data saved ok.";
            }

            

        }
        

    }

    /// <summary>
    /// this function will check if the department exist with the same Name or not
    /// </summary>
    /// <returns>true if ok , false for error (department exist before)</returns>
    protected bool checkForRepeats()
    {
        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);



        List<Folders> lstOldFolders = objFoldersDB.getFoldersByFolderNameAR (objFolders.FolderNameAR);

        List<Folders> lstExist = new List<Folders>(from objOrg in lstOldFolders where (objOrg.ParentID == objFolders.ParentID && objOrg.FolderNameAR == objFolders.FolderNameAR && objOrg.ID != objFolders.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }


        lstOldFolders = objFoldersDB.getFoldersByFolderNameEN(objFolders.FolderNameEN);

        lstExist = new List<Folders>(from objOrg in lstOldFolders where (objOrg.ParentID == objFolders.ParentID && objOrg.FolderNameEN == objFolders.FolderNameEN && objOrg.ID != objFolders.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }
           


       

        return true;

    }


    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {
       
            lblError.Text = "Error , an Course type with the same name and path is already found , choose a new Name or path";
        
    }







    protected void btnSave_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_folders_page))
            return;


        if (Page.IsValid)
        {
            


            ReadAllControls();

           

            


            Save();


        }
    }



    protected void btnDelete_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_folders_page))
            return;


        ReadAllControls();

        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);
        List<Folders> lstFolders = new List<Folders>();
        lstFolders.Add(objFolders);




        if (objFolders.ID == -1)
        {
            lblError.Text = "No Course types to delete";
            lblResult.Text = "";
            return;
        }





        //if (lstFolders[0].lstChild.Count > 0 || lstFolders[0].lstCourses.Count > 0)
        //{
            bool bRet = objFoldersDB.deleteAll(lstFolders[0]);
            if (bRet)
            {
                lblResult.Text = "Deleted ok.";
                clearAllControls();
                fc1.refreshTree();
                fcSelectFolder.refreshTree();
                clearAllControls();
            }
            else
            {
                lblError.Text = "Error Deleting.";
            }
            //return;
        //}


        //objFoldersDB.Delete(lstFolders[0]);



        //lblResult.Text = "Deleted ok.";
       
       





    }


    /// <summary>
    /// this to handle the change in path
    /// </summary>
    /// /// <param name="sender">the control object sended the event</param>
    /// <param name="e">the new path</param>
    protected void fc1_SelectedItemChanged(object sender,CustomEventArgs eObj)
    {
        Folders e = (Folders)eObj.objArgs;
        if (objFolders.ID != -1)
        {
            if (e.ID == objFolders.ID)
            {
                eObj.Cancel = true;
                //if (objFolders.ParentID != null)
                //    fc1.set(objFolders.ParentID.Value);
                //else
                //    fc1.set(-1);


                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert ('This is the folder you are editing');", true);


            }
        }
    }


    /// <summary>
    /// this will handle the selection change in the selected folder control
    /// </summary>
    /// <param name="sender">the object sended this event</param>
    /// <param name="e">the params that contains the selected item</param>
    protected void fcSelectFolder_SelectedItemChanged(object sender, CustomEventArgs e)
    {
        Folders i_objFolder = (Folders)e.objArgs;


        if (i_objFolder != null)
        {
            objFolders = i_objFolder;
            checkID();
            BindAllControls();


        }
        else
        {
            checkID();
            clearAllControls();
        }
    }


    protected void btnNew_Click(object sender, EventArgs e)
    {
        objFolders = new Folders();
        checkID();
        BindAllControls();
        
    }

    



   


}
